<template>
  <ex-dialog
    width="1000px"
    class="ex-diolog"
    :title="title"
    :visible="visible"
    @closeDialog="handleClose"
  >	
		<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm">
      <el-form-item label="广告页面：" prop="advertisePageType">
        <el-select v-model="ruleForm.advertisePageType" placeholder="请选择" size="small" @change="changeAdvertisePage">
          <el-option v-for="item in advertisePageTypeList" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="广告类型：" prop="advertiseType">
        <el-select v-model="ruleForm.advertiseType" placeholder="请选择" size="small">
          <el-option v-for="item in advertiseTypeList" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="广告名称:" prop="name">
				<el-input type="text" v-model="ruleForm.name" autocomplete="off" placeholder="请填写广告名称"></el-input> 
			</el-form-item>
     
      <template v-if="ruleForm.advertiseType == 1">
        <el-form-item label="排序:" prop="sort">
          <el-input type="text" v-model="ruleForm.sort" autocomplete="off" placeholder="请填写排序"></el-input>
        </el-form-item>
        <div class="lable_l">
          <div class="left">轮播图</div>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
        <div class="bannerBox" v-for="(item,index) in ruleForm.bannerList" :key="200+index">
          <div class="imgBox">
            <el-form-item label="轮播图名称:" :prop="`bannerList.${index}.bannerName`" :rules="rules.bannerName">
              <el-input type="text" v-model="item.bannerName" autocomplete="off" placeholder="轮播图名称"></el-input>
            </el-form-item>
            <el-form-item label="是否显示:" :prop="`bannerList.${index}.isShow`" :rules="rules.isShow">
              <el-switch
                v-model="item.isShow"
                active-text="是"
                inactive-text="否"
                active-value="1"
                inactive-value="2">
              </el-switch>
            </el-form-item>
            <el-form-item label="图片:" :prop="`bannerList.${index}.imgUrl`" :rules="rules.imgUrl" ref="imgRef">
              <ImageUploadMore :limit="1" :fileSize="20" @successImg="(e) => {getBannerImg(e,index)}" :value="item.imgUrl	">
              </ImageUploadMore>
            </el-form-item>
            <el-form-item label="跳转链接:" :prop="`bannerList.${index}.redirectType`" :rules="rules.redirectType">
              <el-radio-group v-model="item.redirectType">
                <el-radio label="1">神椰H5</el-radio>
                <el-radio label="2">其他H5</el-radio>
                <el-radio label="3">小程序</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="APPID:" :prop="`bannerList.${index}.appId`" :rules="rules.appId" v-if="item.redirectType == 3">
              <el-input type="text" v-model="item.appId" autocomplete="off" placeholder="请填写APPID"></el-input>
            </el-form-item>
            <el-form-item label="链接地址:" :prop="`bannerList.${index}.redirectUrl`" :rules="rules.redirectUrl">
              <el-input type="text" v-model="item.redirectUrl" autocomplete="off" placeholder="请填写链接地址"></el-input>
            </el-form-item>
            <el-form-item label="APP跳转:" :prop="`bannerList.${index}.appRedirectType`" :rules="rules.appRedirectType">
              <el-select v-model="item.appRedirectType" placeholder="请选择" size="small" @change="(val) => changAppRedirectType(val,index)">
                <el-option v-for="item in appTypeList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" :prop="`bannerList.${index}.appRedirectId`" :rules="rules.appRedirectId" v-if="item.appRedirectType == 1 || item.appRedirectType == 2 || item.appRedirectType == 3 || item.appRedirectType == 4 ">
              <el-select v-model="item.appRedirectId" placeholder="请选择" size="small" filterable>
                <el-option v-for="(aitem,aindex) in item.appRedirectIdList" :key="aindex" :label="aitem.value" :value="aitem.id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="rig_btn_box">
              <el-button type="primary" circle icon="el-icon-arrow-up" @click="upGo(index)" v-if="index != 0"></el-button>
              <el-button type="primary" circle icon="el-icon-arrow-down" @click="downGo(index)" v-if="index != ruleForm.bannerList.length - 1 "></el-button>
              <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(index)"></el-button>
          </div>
        </div>
      </template>
      <template  v-if="ruleForm.advertiseType == 2">
        <div class="oneBox">
          <el-form-item label="是否显示:" prop="isShow">
            <el-switch
              v-model="ruleForm.isShow"
              active-text="是"
              inactive-text="否"
              active-value="1"
              inactive-value="2">
            </el-switch>
          </el-form-item>
          <el-form-item label="图片" prop="imgUrl" ref="imgRef">
            <ImageUploadMore :limit="1" :fileSize="20" @successImg="getImg" :value="ruleForm.imgUrl">
            </ImageUploadMore>
          </el-form-item>
          <el-form-item label="跳转链接:" prop="redirectType">
            <el-radio-group v-model="ruleForm.redirectType">
              <el-radio label="1">神椰H5</el-radio>
              <el-radio label="2">其他H5</el-radio>
              <el-radio label="3">小程序</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="APPID:" prop="appId" v-if="ruleForm.redirectType == 3">
            <el-input type="text" v-model="ruleForm.appId" autocomplete="off" placeholder="请填写APPID"></el-input>
          </el-form-item>
          <el-form-item label="链接地址:" prop="redirectUrl">
            <el-input type="text" v-model="ruleForm.redirectUrl" autocomplete="off" placeholder="请填写链接地址"></el-input>
          </el-form-item>
          <el-form-item label="排序:" prop="sort">
            <el-input type="text" v-model="ruleForm.sort" autocomplete="off" placeholder="请填写排序"></el-input>
          </el-form-item>
        </div>
      </template>
      <template v-if="ruleForm.advertiseType == 3">
        <el-form-item label="是否显示:" prop="isShow">
          <el-switch
            v-model="ruleForm.isShow"
            active-text="是"
            inactive-text="否"
            active-value="1"
            inactive-value="2">
          </el-switch>
        </el-form-item>
        <el-form-item label="选择平台打卡活动：" prop="punchActivityId">
          <el-select v-model="ruleForm.punchActivityId" filterable placeholder="请选择" size="small">
            <el-option v-for="item in activeList" :key="item.id" :label="item.value" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序:" prop="sort">
          <el-input type="text" v-model="ruleForm.sort" autocomplete="off" placeholder="请填写排序"></el-input>
        </el-form-item>
      </template>
			<el-form-item>
				<el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">确认</el-button>
				<el-button @click="handleClose('ruleForm')">取消</el-button>
			</el-form-item>
		</el-form>
  </ex-dialog>
</template>
<script>
// components
import Loading from '@/components/Loading/index'
// api
import {
  adminDict,
  punchActivitySelect,
  addAdvertisement,
  editAdvertisement,
  advertisementInfo,
  bannerSelect
} from '@/api/incentiveManagement/adConfig'

export default {
  components: {
    Loading
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {
    
    return {
      loading: false,
      advertisePageTypeList: [],//广告页面类型
      advertiseTypeList: [],//广告类型
      newadvertiseTypeList: [],
      activeList: [],//打卡活动类型
      roleList: [],
      imgLoading: false,
      appList_1: [],
      appList_2: [],
      appList_3: [],
      appList_4: [],
      appTypeList: [],
			ruleForm: {
        advertisePageType: '',//广告页面 1 神椰页面 2 神椰乐园
        advertiseType: '',//广告类型 1 轮播图 2 单图 3 打卡活动
        name: '',//广告名称
        sort: '',//	排序序号
        appId	: '',//	appId
        id: '',//
        imgUrl: '',//	图片url
        isShow: '1',//是否显示 1 显示 2 不显示
        punchActivityId: '',//打卡活动id
        redirectType: '',//	链接类型（1 神椰 2 H5 3 小程序）
        redirectUrl: '',//指定跳转链接
        bannerList:[
          {
            appId: '',//
            imgUrl: '',//图片url
            isShow: '1',//是否显示 1 显示 2 不显示
            bannerName: '',//轮播图名称
            redirectType: '',//链接类型（1 神椰 2 H5 3 小程序）
            redirectUrl: '',//指定跳转链接
            appRedirectType: '', //APP跳转类型 1打卡活动 2打卡店铺 3神椰NFR 4盲盒活动 5神椰集市 6神椰工厂 7我的邀请码	
            appRedirectId:'', //APP跳转业务id
            appRedirectIdList: [],
          },
        ],
			},
			rules: {
          advertisePageType: [
            { required: true,message: '请选择', trigger: 'change' }
          ],
          advertiseType: [
            { required: true,message: '请选择', trigger: 'change' }
          ],
          name: [
            { required: true,message: '请填写广告名称',trigger: 'blur' }
          ],
          sort: [
            { required: true,message: '请填写排序', trigger: 'change' }
          ],
          isShow: [
            { required: true,message: '请选择', trigger: 'change' }
          ],
          imgUrl: [
            { required: true,message: '请上传图片', trigger: 'change' }
          ],
          appId: [
            { required: true,message: '请填写appId',trigger: 'blur' }
          ],
          punchActivityId: [
            { required: true,message: '请选择', trigger: 'change' }
          ],
          redirectType: [
            { required: true,message: '请选择', trigger: 'change' }
          ],
          redirectUrl: [
            { required: true,message: '请填写链接',trigger: 'blur' }
          ],
          bannerName: [
            { required: true,message: '请填写名称',trigger: 'blur' }
          ],
          appRedirectType: [
            { required: true,message: '请选择', trigger: 'change' }
          ],
          appRedirectId: [
            { required: true,message: '请选择', trigger: 'change' }
          ],
        }
    }
  },
  computed: {
   
  },
  created() {
    this.getadminDict()
    this.getselete()
    this.getAppSelect(1)
    this.getAppSelect(2)
    this.getAppSelect(3)
    this.getAppSelect(4)
    this.ruleForm.id = this.id
    if(this.pathType == 'add'){
      this.title = '新增广告'
      this.ruleForm.id = ''
    }else{
      this.getDatail()
      this.title = '编辑广告'
    }
    
    
	},
  methods: {
    init(){
       this.ruleForm.punchActivityId = ''//打卡活动id
       this.ruleForm.sort = ''
    },
    //获取字典值
    getadminDict() {
      const params = {
        dictType: "bee_shenye_advertisement_config_advertise_page_type,bee_shenye_advertisement_config_advertise_type,app_redirect_type",
      };
      adminDict(params).then((res) => {
        this.advertisePageTypeList = res.result[0].dictList;
        this.newadvertiseTypeList = res.result[1].dictList
        this.advertiseTypeList = res.result[1].dictList
        this.appTypeList = res.result[2].dictList
      });
    },
 
    //app跳转活动
    getAppSelect(type){
      var data = {
        appRedirectType: type
      }
      bannerSelect(data).then(res => {
        if(type == 1){
          this.appList_1 = res.result
        }else if(type == 2){
          this.appList_2 = res.result
        }else if(type == 3){
          this.appList_3 = res.result
        }else if(type == 4){
          this.appList_4 = res.result
        }
      })
    },
    changAppRedirectType(val,index){
      console.log('val',val)
      console.log('index',index)
      if(this.ruleForm.bannerList[index].appRedirectId){
        this.ruleForm.bannerList[index].appRedirectId = null 
      }
      if(val == 1){
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_1
      }else if(val == 2){
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_2
      }else if(val == 3){
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_3
      }else if(val == 4){
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_4
      }
      
    },
    //
    changeAdvertisePage(e){
      console.log('this.newadvertiseTypeList',this.newadvertiseTypeList)
      
      var arr = [...this.advertiseTypeList]
      if(e == 2){
        if(this.ruleForm.advertiseType == 3){
          this.ruleForm.advertiseType = ''
          this.init()
        }
        arr.forEach((item,index) => {
          if(item.id == 3){
            arr.splice(index,1)
            this.advertiseTypeList = arr
            console.log()
          }
        })
      }else{
        this.advertiseTypeList = this.newadvertiseTypeList
      }
      
    },
    //查询神椰打卡活动下拉框
    getselete(){
      punchActivitySelect().then(res => {
        this.activeList = res.result
      })
    },
    //获取详情
    getDatail(){
      var id = this.id
      advertisementInfo(id).then(res => {
        this.ruleForm = res.result
        this.ruleForm.bannerList = this.ruleForm.bannerList.map((item,index) => {
          if(item.appRedirectType == 1){
            item.appRedirectIdList = this.appList_1
          }else if(item.appRedirectType == 2){
            item.appRedirectIdList = this.appList_2
          }else if(item.appRedirectType == 3){
            item.appRedirectIdList = this.appList_3
          }else if(item.appRedirectType == 4){
            item.appRedirectIdList = this.appList_4
          }
          return item
        })
      })
    },
    /** logo */
    getImg(e) {
      this.ruleForm.img = e
      this.$refs['imgRef'].clearValidate();
    },
    //新建子账号
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          if(this.pathType == 'add'){
            var data = {
            ...this.ruleForm
            }
            addAdvertisement(data).then(res => {
             
              setTimeout(() => {
                this.handleClose()
                this.$message.success('创建成功')
                this.$emit('success')
                this.loading = false
              }, 1000);
            }).catch(()=> {
              this.loading = false
            }).finally(() => {

            })
          }else if(this.pathType == 'edit'){
            var data = {
            ...this.ruleForm
            }
            editAdvertisement(data).then(res => {
              setTimeout(() => {
                this.$message.success('修改成功')
                this.handleClose()
                this.$emit('success')
                this.loading = false
              }, 1000);
            }).catch(()=> {
              this.loading = false
            }).finally(() => {

            })
          }
            
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    
		//取消
    handleClose(formName) {
      this.$emit('update:visible', false)
			// this.$refs[formName].resetFields();
    },
		//确认
		handleConfirm(){
			this.$emit('success', '你好')
		},
    handleSuccess(msg) {
      if (msg === '已拒绝') {
        var type = 'error'
      } else {
        var type = 'success'
      }
      this.$message({
        message: msg,
        type: type,
        duration: 1500,
        onClose: () => {
          this.handleClose()
          this.$emit('success')
        }
      })
    },
    //新增轮播图
    handleAdd(){
      var obj = {
            appId: '',//
            imgUrl: '',//图片url
            isShow: '1',//是否显示 1 显示 2 不显示
            bannerName: '',//轮播图名称
            redirectType: '',//链接类型（1 神椰 2 H5 3 小程序）
            redirectUrl: '',//指定跳转链接
          }
      this.ruleForm.bannerList.push(obj)
    },
    //删除轮播图
    handleDelete(ind){
      this.ruleForm.bannerList.splice(ind,1)
    },
    //轮播图广告上传图片
    getBannerImg(e,index){
      this.ruleForm.bannerList[index].imgUrl = e
    },
    //上传图片
    getImg(e){
      this.ruleForm.imgUrl = e
      this.$refs['imgRef'].clearValidate();
    },
    //上移一位
    upGo(index) {
      console.log('index',index)
      var arr = this.ruleForm.bannerList
      if (index != 0) {
        // console.log(arr.splice(index - 1, 1, arr[index][0]))
        this.ruleForm.bannerList[index] = arr.splice(index - 1, 1, arr[index])[0]
        console.log('arr',arr)
      } else {
        this.ruleForm.bannerList.push(arr.shift())
      }
    },
    //下移一位
    downGo(index) {
      var arr = this.ruleForm.bannerList
      if (index != arr.length - 1) {
        this.ruleForm.bannerList[index] = arr.splice(index + 1, 1, arr[index])[0]
      } else {
        this.ruleForm.bannerList.unshift(arr.splice(index, 1)[0])
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
		padding: 0 !important;
  }
	::v-deep .ex--dialog--main {
    padding: 10px 20px !important; 
  }
}
::v-deep .avatar-uploader2 .el-upload {
  width: 100% !important;
}

.avatar-uploader2 {
  width: 130px;
  height: 130px;
  text-align: center;
  line-height: 130px;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
}

.banner_img {
  width: 130px;
  height: 130px;
}
.el-input{
  width: 300px;
}
.lable_l{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 20px 0 20px 80px ;
  .left{
    margin-right: 20px;
  }
}
.bannerBox{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  .rig_btn_box{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    width: 100px;
    height: 200px;
    .el-button{
      margin: 0 ;
    }
  }
}
.imgBox{
  border: 1px solid #f5f5f5;
  border-radius: 12px;
  padding: 20px;
  width: 800px;
  .name{
    font-size: 16px;
    color: #606266;
    margin-bottom: 10px;
    padding-left: 50px;
  }
}
</style>